﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace TweetMemeNET
{
    /// <summary>
    /// Base class for all TweetMeme API calls
    /// </summary>
    public abstract class TweetMemeCallBase
    {
        // The URL of the website or page to look up on TweetMeme
        private string _siteUrl;

        // The result of the TweetMeme API call
        private ITweetMemeResult _result;

        /// <summary>
        /// Creates a new TweetMeme API call for the specified URL
        /// </summary>
        /// <param name="url"></param>
        public TweetMemeCallBase(string siteUrl)
        {
            SiteURL = siteUrl;

            CallTweetMeme();
        }

        /// <summary>
        /// Constructor for calls not requiring a specific site or page URL
        /// </summary>
        public TweetMemeCallBase()
        {
            CallTweetMeme();
        }

        protected void CallTweetMeme()
        {
            try
            {
                WebClient wc = new WebClient();

                // Connect to TweetMeme and retrieve the result
                _result = HandleResult(wc.DownloadString(GetTweetMemeApiUrl()));
            }
            catch (WebException ex)
            {
                throw new TweetMemeException("Unable to connect to the TweetMeme API. The service may be down, or there's no available internet connection.", ex);
            }
        }

        public string SiteURL
        {
            get { return _siteUrl; }
            protected set
            {
                // Verify it's a valid URL
                Uri uri = new Uri(value);

                _siteUrl = uri.ToString(); 
            }
        }

        public virtual ITweetMemeResult Result
        {
            get { return _result; }
            protected set { _result = value; }
        }

        /// <summary>
        /// Composes the URL for the TweetMeme API call using the specified page URL
        /// </summary>
        /// <returns></returns>
        protected abstract string GetTweetMemeApiUrl();

        /// <summary>
        /// Handles the result as returned by the TweetMeme API
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        protected abstract ITweetMemeResult HandleResult(string result);
    }
}
